// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const usersDb = cloud.database().collection('users')
  // 根据 user 的 keepTime 最大值 为其续借
  const userData = await usersDb.where({
    openid
  }).get()
  const user = userData.data[0]
  user.books.forEach(item => {
    if (item.bookId === event.bookId) {
      item.borrowTime = Date.now()
    }
  })
  delete user._id
  await usersDb.where({
    openid
  }).update({
    data: user
  })
  return {
    status: 0,
    msg: '续借成功'
  }
}